package com.zlm.config;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

import javax.annotation.Resource;

/**
 * 自定义授权服务器配置类(基于内存的)
 */

//@Configuration
//@EnableAuthorizationServer // 作为授权服务器
public class inMemoryAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 配置客户端详情信息
     * 可以为那些第三方应用颁发令牌，可以配置多个
     * id secret
     * redirectURI 授权码模式
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("client")
                .secret(passwordEncoder.encode("secret")) // 密钥
                .redirectUris("http://www.baidu.com")
                .authorizedGrantTypes("authorization_code", "refresh_token", "implicit", "password", "client_credentials") // 授权码模式  refresh_token 刷新令牌
                .scopes("read:user"); // 作用域 令牌允许获得的权限
    }

    /**
     * 配置令牌访问端点
     * 配置使用哪个userDetailService来进行令牌的刷新
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.userDetailsService(userDetailsService); // 配置userDetailsService来获取用户的信息
        endpoints.authenticationManager(authenticationManager); // 配置认证管理器来进行认证
    }

    // 授权码这种模式： 1.请求用户是否授权 /oauth/authorize
    // 完整路径：http://localhost:8080/oauth/authorize?client_id=client&response_type=code&redirect_uri=http://www.baidu.com
    //              2.授权之后根据获取的授权码获取令牌 /oauth/token
    // 完整路径：http://localhost:8080/oauth/token?grant_type=authorization_code&code=授权码&redirect_uri=http://www.baidu.com&client_id=client&client_secret=secret
}
